package asynqQueueClient

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/hibiken/asynq"
	"seawolf-admin-go/utility/asynq/asynqQueue"
	"sync"
	"time"
)

var client *asynq.Client
var once sync.Once

// 初始化客户端
func initClient(ctx context.Context) {
	client = asynq.NewClient(
		asynqQueue.GetRedisClientOpt(ctx),
	)
}

// GetClient 获取客户端，单例模式
func GetClient() *asynq.Client {
	once.Do(func() {
		initClient(context.Background())
	})

	return client
}

func getOption(ctx context.Context, topic asynqQueue.WorkflowTopicType) []asynq.Option {
	switch topic {
	case asynqQueue.UserConfirmScore:
		tmpDelayTime, _ := g.Cfg().Get(ctx, "queue."+asynqQueue.WorkflowTopicName[topic]+".DelayTime", 1)
		tmpMaxRetry, _ := g.Cfg().Get(ctx, "queue."+asynqQueue.WorkflowTopicName[topic]+".MaxRetry", 3)
		return []asynq.Option{
			asynq.ProcessIn(tmpDelayTime.Duration() * time.Second), // 多少秒后执行
			asynq.MaxRetry(tmpMaxRetry.Int()),                      // 最大重试次数
		}
	default:
		return []asynq.Option{
			asynq.ProcessIn(1 * time.Second), // 多少秒后执行
			asynq.MaxRetry(3),                // 最大重试次数
		}
	}
}

func GetTask(ctx context.Context, topic asynqQueue.WorkflowTopicType, payload []byte) *asynq.Task {
	return asynq.NewTask(asynqQueue.WorkflowTopicName[topic], payload, getOption(ctx, topic)...)
}
